import { Router } from 'express';
import { body } from 'express-validator';
import validateFormData from '../helpers/validate_form.js';
import DB from '../models/db.js';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import { apiAuth } from '../helpers/api_auth.js';
import fs from 'fs';
import EthersUtils from '../helpers/ethers_utils.js';
import config from '../config.js';

const router = Router();
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

/**
 * 快速查询成绩报告（数据库查询）
 * @GET /api/grade-reports/quick-query
 */
router.get('/quick-query', apiAuth, async (req, res) => {
    try {
        const { semester, ethereum_address } = req.query;

        if (!semester || !ethereum_address) {
            return res.status(400).json({
                success: false,
                message: '学期和以太坊地址不能为空'
            });
        }

        // 联表查询用户和成绩汇总
        const report = await DB.Studentgradesummary.findOne({
            where: {
                semester_name: semester
            },
            include: [{
                model: DB.Users,
                as: 'student',
                where: {
                    ethereum_address: ethereum_address
                },
                attributes: ['user_id', 'name', 'ethereum_address']
            }],
            attributes: [
                'summary_id',
                'semester_name',
                'data_hash',
                'transaction_hash',
                'onchain_status',
                'onchain_time',
                'cid',
                'registrar_sig',
                'student_sig',
                'confirm_status'
            ]
        });

        if (!report) {
            return res.status(404).json({
                success: false,
                message: '未找到相关成绩报告'
            });
        }

        return res.json({
            success: true,
            data: report
        });
    } catch (error) {
        console.error('查询成绩报告失败:', error);
        return res.status(500).json({
            success: false,
            message: '查询成绩报告失败'
        });
    }
});

/**
 * 通过区块链查询成绩报告
 * @GET /api/grade-reports/blockchain-query
 */
router.get('/blockchain-query', apiAuth, async (req, res) => {
    try {
        const { semester, ethereum_address } = req.query;

        if (!semester || !ethereum_address) {
            return res.status(400).json({
                success: false,
                message: '学期和以太坊地址不能为空'
            });
        }

        // 初始化以太坊工具
        const ethersUtils = new EthersUtils(config.eth.privateKey);

        // 获取合约实例
        // 从数据库获取最新的逻辑合约地址
        const latestContract = await DB.SmartContracts.findOne({
            where: {
                category: 'operation'
            },
            order: [['date_created', 'DESC']]
        });

        if (!latestContract) {
            return res.badRequest('No logic contract found in database');
        }


        const logicContractPath = path.resolve(
            __dirname,
            '../helpers/build/contracts/GradeLogicV1.json'
        );

        if (!fs.existsSync(logicContractPath)) {
            return res.badRequest('Logic contract ABI not found');
        };

        const logicContractData = JSON.parse(fs.readFileSync(logicContractPath, 'utf8'));


        const contract = ethersUtils.getContract(latestContract.contract_address, logicContractData.abi);

        // 调用合约查询方法
        const report = await contract.getReport(ethereum_address, semester);

        // 解析返回结果
        const [cid, confirmed, updateTime, registrarSigner, studentSigner] = report;

        return res.json({
            success: true,
            data: {
                cid,
                confirmed,
                updateTime: new Date(Number(updateTime) * 1000).toISOString(),
                registrarSigner,
                studentSigner
            }
        });
    } catch (error) {
        console.error('区块链查询成绩报告失败:', error);
        return res.status(500).json({
            success: false,
            message: '区块链查询成绩报告失败'
        });
    }
});

export default router; 